package cn.yqm.modules.service;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.yqm.common.LoginInterface;
import cn.yqm.common.UserModel;
import cn.yqm.common.YqmProperties;
import cn.yqm.common.YqmSessionUtils2;
import cn.yqm.common.enums.YqmLoginEnum;
import cn.yqm.common.exception.YqmException;
import cn.yqm.dto.YqmSysUserDto;
import cn.yqm.entity.YqmSysUser;
import cn.yqm.req.YqmSysUserReq;
import cn.yqm.service.IYqmSysUserService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 账号密码登录
 *
 * @author weiximei
 * @domain www.yqmshop.cn
 * @since 2023/7/23
 */
@AllArgsConstructor
@Component
public class UsernamePasswordLoginImpl implements LoginInterface {

    private final IYqmSysUserService iYqmSysUserService;
    private final YqmProperties yqmProperties;

    @Override
    public String loginType() {
        return YqmLoginEnum.USER_PWD.getValue();
    }

    @Override
    public Object login(String account, String password, Boolean remember) {
        YqmSysUserDto sysUserDto = YqmSysUserDto.builder().build();

        YqmSysUser user = iYqmSysUserService.getOne(iYqmSysUserService.getQuery(YqmSysUserReq.builder().userName(account).build()));
        if (Objects.isNull(user) || StringUtils.isEmpty(password)) {
            throw new YqmException("账户或密码错误");
        }

        String yPassword = SaSecureUtil.aesEncrypt(yqmProperties.getCipherKey(), password);
        if (!StringUtils.equals(yPassword, user.getPassword())) {
            throw new YqmException("账户或密码错误");
        }

        StpUtil.login(user.getUserId(), BooleanUtils.toBooleanDefaultIfNull(remember, false));

        UserModel userModel = UserModel.builder().id(String.valueOf(user.getUserId())).account(user.getUserName()).build();
        YqmSessionUtils2.setSessionUser(userModel);

        return StpUtil.getTokenInfo();
    }
}
